#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_io.h"

// GPIO9控制LED
#define LED_TASK_GPIO 9
// GPIO5控制按键
#define BUTTON_TASK_GPIO 14

#define LED_INTERVAL_TIME 30
#define LED_TASK_STACK_SIZE 512
#define LED_TASK_PRIO 25

enum LedState
{
    LED_ON = 0,
    LED_OFF,
    LED_SPARK,
};

enum LedState g_ledState = LED_SPARK;

static void LedTask()
{
    while (1)
    {
        switch (g_ledState)
        {
        case LED_ON:
            // 控制灯开
            IoTGpioSetOutputVal(LED_TASK_GPIO, 0);
            break;
        case LED_OFF:
            // 控制灯关
            IoTGpioSetOutputVal(LED_TASK_GPIO, 1);
            break;
        case LED_SPARK:
            // 控制灯闪
            IoTGpioSetOutputVal(LED_TASK_GPIO, 0);
            osDelay(LED_INTERVAL_TIME);
            IoTGpioSetOutputVal(LED_TASK_GPIO, 1);
            osDelay(LED_INTERVAL_TIME);
            break;
        }
    }
}

static void OnButtonPressed()
{
    static int cnt = 0;
    enum LedState nextState = LED_SPARK;
    switch (g_ledState)
    {
    case LED_ON:
        nextState = LED_SPARK;
        break;
    case LED_OFF:
        nextState = LED_ON;
        break;
    case LED_SPARK:
        nextState = LED_OFF;
        break;
    default:
        break;
    }
    g_ledState = nextState;
}

static void LedExampleEntry(void)
{
    // LED的GPIO9初始化
    IoTGpioInit(LED_TASK_GPIO);
    hi_io_set_func(LED_TASK_GPIO, HI_IO_FUNC_GPIO_9_GPIO);
    // 设置为输出
    IoTGpioSetDir(LED_TASK_GPIO, IOT_GPIO_DIR_OUT);

    // 按键GPIO5初始化
    IoTGpioInit(BUTTON_TASK_GPIO);
    // 模式设置为标准GPIO
    hi_io_set_func(BUTTON_TASK_GPIO, HI_IO_FUNC_GPIO_14_GPIO);
    // 设置为输入
    IoTGpioSetDir(BUTTON_TASK_GPIO, IOT_GPIO_DIR_IN);
    // 拉高GPIO5电平等待后续按键事件触发
    hi_io_set_pull(BUTTON_TASK_GPIO, HI_IO_PULL_UP);
    // 注册按键中断处理函数
    IoTGpioRegisterIsrFunc(BUTTON_TASK_GPIO, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_RISE_LEVEL_HIGH, OnButtonPressed, NULL);

    osThreadAttr_t attr;

    attr.name = "LedTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = LED_TASK_STACK_SIZE;
    attr.priority = LED_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)LedTask, NULL, &attr) == NULL)
    {
        printf("[LedExample] Falied to create LedTask!\n");
    }
}

SYS_RUN(LedExampleEntry);
